

import os
import time
import random

from dexen import SlaveTask

import common
from my_ind import MyInd

def sim_display(filename):
    common.enableHouModule()
    import hou
    basefile = os.path.join(common.HOUDINI_BASE_FILE, filename)
    display_result_geom = os.path.join(common.HOUDINI_BASE_FILE, "display_result_geom")
    if not os.path.isdir(display_result_geom):
        os.mkdir(display_result_geom)
    
    
    file_path = os.path.join(display_result_geom, "temp.bgeo")
    print "I am before load()"    
    hou.hipFile.load(basefile)
    print "I am after load()"
    hou.node("/obj/geo1/OUT").cook()
    print "I am after cook()"
    hou.node("/obj/geo1/OUT").geometry().saveToFile(file_path)

    f = open(file_path, "r")
    output = f.read()
    f.close()
    return output


#houdini geometry
def develop(ind, file_name):
    assert isinstance(ind, MyInd)
    common.enableHouModule()
    import hou
    basefile = os.path.join(common.HOUDINI_BASE_FILE, file_name)
    hou.hipFile.load(basefile)
    genotype = hou.node("/obj/geo1/genotypes")
    for cnt in range(len(ind.genotype)):
        genotype.setParms(dict([["genotype"+str(cnt+1),ind.genotype[cnt]]]))
        
    phenotype_geom = os.path.join(common.HOUDINI_BASE_FILE, "phenotype")
    if not os.path.isdir(phenotype_geom):
        os.mkdir(phenotype_geom)
    file_path = os.path.join(phenotype_geom, "temp.bgeo")
    hou.node("/obj/geo1/phenotype").geometry().saveToFile(file_path)
    
    f = open(file_path, "r")
    phenotype = f.read()
    f.close()
    return phenotype
    
def dummy_develop():
    return "Genotype"

class DevTask(SlaveTask):
    def __init__(self):
        pass
    
    def __execute__(self, master_state, inds):
        print "I am in development"
        for ind in inds:
            assert isinstance(ind, MyInd)
            #ind.phenotype = dummy_develop()
            ind.phenotype = develop(ind, "houseschema.hipnc")
            print "I am after develop()"
            data = sim_display("display_geom.hipnc")
            print "I am after sim_display()"
            ind.archive_data("houseschema.bgeo", data)
        return inds


